from rest_framework import serializers
from django_redis import get_redis_connection

from oauth.utils import check_save_user_token
from users.models import User
from .models import OAuthQQUser

class QQAuthUserSerializer(serializers.Serializer):
    # 定义需要序列化或反序列化的字段
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    # 校验
    def validate(self, data):
        # 获取ｏｐｅｎｉｄ
        openid_token = data.get('access_token')
        openid = check_save_user_token(openid_token)
        if not openid:
            raise serializers.ValidationError('access_token无效')
        data['openid'] = openid

        # 获取ｒｅｄｉｓ中的短信验证码跟用户填写的做判断
        sms_code = data.get('sms_code')  # 获取前端传来的短信验证码
        redis_conn = get_redis_connection('verify_code')
        real_sms_code = redis_conn.get('sms_%s' % data.get("mobile"))
        if real_sms_code.decode() != sms_code:
            raise serializers.ValidationError('sms_code错误')

        # 用手机号查询用户
        try:
            user = User.objects.get(mobile=data.get('mobile'))
        except User.DoesNotExist:
            # 手机号不存在说明是个新的用户
            pass
        else:
            if not user.check_password(data.get('possword')):
                raise serializers.ValidationError('密码不正确')
            else:
                # 把用户直接加到反序列化的大字典中，已被后用
                data['user'] = user

        return data
    # 重写ｃｒｅａｔｅ的方法
    def create(self, validated_data):
        # 从validated_data来获取user,如果能取到,说明当前用户是已存在的(直接和open绑定)
        user = validated_data.get('user')
        if not user:  # 如果用户不存在,就新增一个用户
            user = User.objects.create(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile']
            )

        # openid关联user
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )

        return user  # 把user因为后续生成jwt token需要使用
